package org.wangchaocheng.cloudgallery.user.gatewayimpl;

import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Repository;
import org.wangchaocheng.cloudgallery.dto.user.UserAuthenticationDTO;
import org.wangchaocheng.cloudgallery.user.converter.UserAuthenticationConverter;
import org.wangchaocheng.cloudgallery.user.dataObject.UserAuthenticationDO;
import org.wangchaocheng.cloudgallery.user.gateway.UserAuthenticationGateway;
import org.wangchaocheng.cloudgallery.user.mapper.UserAuthenticationMapper;

/**
 * @author wangchaocheng
 * @date 2025/04/08
 */
@Repository
public class UserAuthenticationGatewayImpl extends ServiceImpl<UserAuthenticationMapper, UserAuthenticationDO> implements UserAuthenticationGateway {
    @Override
    public void save(UserAuthenticationDTO userAuthenticationDTO) {
        UserAuthenticationDTO existUserAuthentication = this.findByIdentifier(userAuthenticationDTO.getIdentifier());
        // 模型转换
        UserAuthenticationDO userAuthenticationDO = UserAuthenticationConverter.INSTANCE.dto2Do(userAuthenticationDTO);
        // 如果不存在，则保存
        if (Objects.isNull(existUserAuthentication)) {
            this.save(userAuthenticationDO);
        } else {
            // 如果存在，则更新
            userAuthenticationDO.setId(existUserAuthentication.getId());
            this.updateById(userAuthenticationDO);
        }
    }

    @Override
    public void removeByUserId(Long userId) {
        LambdaQueryWrapper<UserAuthenticationDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAuthenticationDO::getUserId, userId);
        this.baseMapper.delete(queryWrapper);
    }

    @Override
    public void removeByIdentifier(String identifier) {
        LambdaQueryWrapper<UserAuthenticationDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAuthenticationDO::getIdentifier, identifier);
        this.baseMapper.delete(queryWrapper);
    }

    @Override
    public UserAuthenticationDTO findByIdentifier(String identifier) {
        LambdaQueryWrapper<UserAuthenticationDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAuthenticationDO::getIdentifier, identifier);
        UserAuthenticationDO userAuthenticationDO = this.baseMapper.selectOne(queryWrapper);
        return UserAuthenticationConverter.INSTANCE.do2Dto(userAuthenticationDO);
    }

    @Override
    public List<UserAuthenticationDTO> listByUserId(Long userId) {
        LambdaQueryWrapper<UserAuthenticationDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAuthenticationDO::getUserId, userId);
        List<UserAuthenticationDO> userAuthenticationDOList = this.baseMapper.selectList(queryWrapper);
        return UserAuthenticationConverter.INSTANCE.doList2DtoList(userAuthenticationDOList);
    }
}
